import {ComponentType} from 'react'
import Taro, {Component} from '@tarojs/taro'
import {View, Swiper, SwiperItem, Image, Text, Button} from '@tarojs/components'
import {observer, inject} from '@tarojs/mobx'
import {
  pageSize,
  formatNumber,
  navigateTo,
  getWechatCode,
  getUserInfo,
  serverHost,
  redirectTo,
  setStorage, setUserInfo, showModel, getStorage, subTime, showToast, stringPartOf
} from "../../utils/common";
import {ProductsOutput, BannerOutput, RecordOutput, RecordOutput} from '../../api/api'

import FooterMenu from "../../components/FooterMenu";

import './index.scss'

import nav_01 from '../../assets/img/nav_01.png'
import nav_02 from '../../assets/img/nav_02.png'
import nav_03 from '../../assets/img/nav_03.png'
import nav_04 from '../../assets/img/nav_04.png'
import nav_05 from '../../assets/img/nav_05.png'

import {IStoreProps} from '../../store/Stores'

interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class Index extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    nav: [
      {title: '每日签到', url: '/pages/mine/sign', icon: nav_01},
      {title: '邀请好友', url: '/pages/share/index', icon: nav_02},
      {title: '动态资讯', url: '/pages/dynamic/index', icon: nav_03},
      {title: '鱼塘VR', url: '/pages/vr/vr', icon: nav_04},
      {title: '帮助中心', url: '/pages/mine/help', icon: nav_05},
    ],
    pageIndex: 1,
    pageSize: pageSize,
    items: [] as ProductsOutput[],
    totalCount: 0,
    bannerList: [] as BannerOutput[],
    periodsNum: '' , // 当前期数
    buyLog: [] as RecordOutput[], // 用户购买记录
  }

  async componentWillMount() {
    let userInfo = getUserInfo()

    console.log(userInfo)

    await this.getItems()
    await this.getBanner()
    let code: string = this.$router.params.code || ''
    let sourceUserId: string = this.$router.params.sourceUserId
    if(sourceUserId) {
      setStorage('sourceUserId', {sourceUserId})
    }
    if (Object.keys(userInfo).length <= 0) {
      if (code.length <= 0) {
        getWechatCode()
        setStorage('weChatCode', {code})
      } else {
        this.getWechatUserInfo()
      }
    }
  }

  componentDidMount(): void {
  }

  componentDidShow() {
    const userInfo = getUserInfo() || {}

    if(Object.keys(userInfo).length > 0 && userInfo.token){
      // 判断登录信息是否过期，过期清除用户信息缓存，重新授权登录
      let now = new Date()
      let nowTime = now.getTime()
      let expire = userInfo.expire
      console.log(nowTime)
      console.log(expire)
      if(nowTime >= expire) { 
        showToast('登录信息已过期')
        Taro.removeStorageSync('user')
      }
    }

    if(Object.keys(userInfo).length > 0 && userInfo.token){
      let { userStore } = this.props.stores
      userStore.getUserInfoAsync({
        callback: res => {
          res.token = userInfo.token
          res.expire = userInfo.expire
          setUserInfo(res)
        }
      })
    }
  }

  getBanner() {
    let {homeStore} = this.props.stores
    homeStore.bannerList({
      callback: res => {
        this.setState({bannerList: res.items || []})
      }
    })
  }

  getWechatUserInfo = () => {
    let code: any = this.$router.params.code || ''
    let sourceUserId = getStorage('sourceUserId')&&getStorage('sourceUserId').sourceUserId || '00000000-0000-0000-0000-000000000000'
    // 获取用户信息, 判断用户是否关注公众号
    if (code) {
      let fetchUrl = `${serverHost}/api/services/app/FrontUser/LoginAsync`
      fetch(fetchUrl, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          code,
          sourceUserId,
        })
      }).then(response => {
        return response.json()
      }).then(res => {
        // 缓存用户信息，有效期5天
        let ymtx_userInfo = res.result
        let now = new Date()
        let nowTime = now.getTime() // 登录时的时间戳，毫秒
        now.setTime(nowTime + 5 * 24 * 60 * 60 * 1000 )
        // now.setTime(nowTime + 1 * 60 * 1000 )
        ymtx_userInfo.expire =  now.getTime()
        setUserInfo(ymtx_userInfo)
        // 清除父级ID
        Taro.removeStorageSync('sourceUserId')
        if (res.result.subscribe == "0") { // 未关注
          redirectTo('/pages/share/qrCode')
        }
      }).catch(e => {
        console.error(e)
      })
    }
  }

  getItems() {
    let {fishStore} = this.props.stores
    let {pageIndex, pageSize} = this.state
    fishStore.getProductsAsync({
      pageIndex,
      pageSize,
      callback: res => {
        res.items&&res.items.map(item => {
          this.getBuyLog(item.id)
          this.setState({ periodsNum: item.id })
        })
        if (this.state.pageIndex === 1) {
          this.setState({totalCount: res.totalCount, items: res.items})
        } else {
          const {items} = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }

  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getItems()
      })
    }
  }

  link = (url: string) => {
    navigateTo(url)
  }

  getBuyLog(id: string) {
    let { fishStore } = this.props.stores
    let { pageIndex } = this.state
    fishStore.userOrderRecordPage({
      productId: id,
      pageIndex,
      pageSize: 15,
      callback: res => {
        this.setState({ buyLog: res.items})
      }
    })
  }

  render() {
    let {nav, items, bannerList, buyLog } = this.state
    return (
      <View className='index yy-index page-bg'>
        <View className='swiper-wrap'>
          <Swiper className='swiper-wrap__item' indicatorColor='#eeeeee' indicatorActiveColor='#fff' indicatorDots autoplay={true} circular interval={2500} duration={600} >
            {bannerList && bannerList.map(item => {
              return (
                <SwiperItem className='swiper-item' key={item.id}>
                  <Image className='swiper-wrap__img' src={item.imgUrl} />
                </SwiperItem>
              )
            })}
          </Swiper>
        </View>

        {
          buyLog.length > 0&&
          <Swiper
              className='swiper-notice'
              vertical
              circular
              autoplay={true}
              interval={1500}
              duration={400}
          >
            {
              buyLog.map((item, index) => {
                return(
                  <SwiperItem className='swiper-notice__item' key={'buylog'+index}>
                    <View className='swiper-notice__con text-overflow'>{`【${stringPartOf(item.nickName || '', 3)}】在${subTime(item.payTime)}联养了`}<Text className='color-theme'>{item.productQuantity}</Text>条</View>
                  </SwiperItem>
                )
              })
            }
          </Swiper>
        }
        <View className='index-nav'>
          {
            nav.map(item => {
              return (
                <View className='index-nav__item' onClick={this.link.bind(this, item.url)}>
                  <Image className='index-nav__icon' src={item.icon}/>
                  <Text className='index-nav__title'>{item.title}</Text>
                </View>
              )
            })
          }
        </View>
        {
          items.length <= 0 && <View className='desc' style={{padding: 20}}>暂时没有相关产品信息~</View>
        }
        {
          items.length > 0 &&
          items.map(item => {
            let fenzi = item.surplusNumber || 0
            let fenmu = item.productNumber || 0
            let prograssWidth = fenmu === 0 ? '0%' : ((fenzi / fenmu) * 100).toFixed(2) + '%'
            let tplOpening =
              <View className='list01__item' key={item.id}
                    onClick={this.link.bind(this, '/pages/fish/detail?id=' + item.id)}>
                <Image className='list01__img' src={item.comImg || ''}/>
                <View className='list01__info'>
                  <View className='list01__line list01__line-sd'>
                    <Text className='list01__date'>第{formatNumber(item.periodsNum || 0)}期</Text>
                    <Text className='list01__title text-overflow'>{item.comName}</Text>
                  </View>
                  <View className='list01__line list01__line-prograss'>
                    <View className='list01__ww'>
                      <View className='list01__prograss'/>
                      <View className='list01__prograss-top' style={{width: prograssWidth}}/>
                    </View>
                    <Text className='list01__percentage'>{prograssWidth}</Text>
                  </View>
                  <View className='list01__line list01__line-i sss' style={{justifyContent: 'spaceBetween'}}>
                    <View className='list01__i'>
                      <View className='list01__price yuan'>{item.unitPrice}</View>
                      <View className='list01__i-title'>单价</View>
                    </View>
                    <View className='list01__i'>
                      <View className='list01__price'>{item.productNumber}</View>
                      <View className='list01__i-title'>总条数</View>
                    </View>
                    {/* <View className='list01__i'>
                      <View className='list01__price'>{item.surplusNumber}</View>
                      <View className='list01__i-title'>剩余条数</View>
                    </View>*/}
                    <View className='list01__btn'>去养鱼</View>
                  </View>
                </View>
              </View>
            let tplEnded =
              <View className='list01__item list01__item-disabled' key={item.id}>
                <Image className='list01__img' src={item.comImg || ''}/>
                <View className='list01__info'>
                  <View className='list01__line list01__line-sd'>
                    <Text className='list01__date'>第{formatNumber(item.periodsNum || 0)}期</Text>
                    <Text className='list01__title text-overflow'>{item.comName}</Text>
                  </View>
                  <View className='list01__line list01__line-prograss'>
                    <View className='list01__ww'>
                      <View className='list01__prograss'/>
                      <View className='list01__prograss-top' style={{width: prograssWidth}}/>
                    </View>
                    <Text className='list01__percentage'>{prograssWidth}</Text>
                  </View>
                  <View className='list01__line list01__line-i' style={{justifyContent: 'spaceBetween;'}}>
                    <View className='list01__i'>
                      <View className='list01__price yuan'>{item.unitPrice}</View>
                      <View className='list01__i-title'>单价</View>
                    </View>
                    <View className='list01__i'>
                      <View className='list01__price'>{item.productNumber}</View>
                      <View className='list01__i-title'>总条数</View>
                    </View>
                    {/* <View className='list01__i'>
                      <View className='list01__price'>{item.surplusNumber}</View>
                      <View className='list01__i-title'>剩余条数</View>
                    </View>*/}
                    <View className='list01__btn'>已售完</View>
                  </View>
                </View>
              </View>
            let tpl = item.isEnd ? tplEnded : tplOpening
            return tpl
          })
        }
        <View className='footer-block' />
        <FooterMenu menu='index' />
      </View>
    )
  }
}

export default Index as ComponentType
